// 云函数入口文件
const cloud = require('wx-server-sdk')
const rp = require('request-promise')
cloud.init()

async function fetchData(form) {
  let response = await rp({
    uri: 'https://www.cyber-cynic.online/csust/tasks',
    form: form,
    method: 'POST'
  })
  return response 
}

// async function getAllSubscribe(dbContext) {
//   return await dbContext.get()
// } 

// 剩余时间提醒
const WARNING_THRESHOLD = 48
const TEMPLATE_ID = 'utDTJifOEsagqbgQBrC-lnGUt5DtBvkjMaHzGXCvYRg'


// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const db = cloud.database()
  const subscribe = db.collection('subscribe')

  // 设置最大fetch个数
  let subscribes = await subscribe.get()

  subscribes.data.forEach(ele => {
    // console.log(ele)
      fetchData({
        username: ele.username,
        passwd: ele.passwd
      }).then(res => {
        let courses = eval(res)
        console.log(courses)
        courses.forEach(course => {
          let tasks = course.tasks

          tasks.forEach(task => {
            if (task.content_sorted.hourRemaining < WARNING_THRESHOLD && task.content_sorted.hourRemaining > 0) {
              // TODO send notifications here
              console.log(task.content_sorted)
            }
          })
        })

      })
      
  });

  // let data = await fetchData({
  //   username: '201908170113',
  //   passwd: 'CODEcode-123'
  // })

  // const result = await cloud.openapi.subscribeMessage.send({
  //   "touser": 'oxMzf4tri7NPkOZHrJh90EYX9M0M',
  //   "page": 'index',
  //   "lang": 'zh_CN',
  //   "data": {
  //     "thing2": {
  //       "value": '作业名称'
  //     },
  //     "time3": {
  //       "value": '2015年01月05日'
  //     },
  //     "thing4": {
  //       "value": '发布人员'
  //     },
  //     "thing1": {
  //       "value": '提醒内容'
  //     }
  //   },
  //   "templateId": 'utDTJifOEsagqbgQBrC-lnGUt5DtBvkjMaHzGXCvYRg',
  //   "miniprogramState": 'developer'
  // })

  // console.log(`${Date.now()}`)

  // return Date.now()
  return subscribes
}